//
//  JPhotoViewerVC.swift
//  JMicroBlog
//
//  Created by Jason on 24/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

// MARK: - 单张照片的控制器
// 主要提供一个张照片 放大缩小查看等功能
class JPhotoViewerVC: UIViewController {

    // 照片缩放的比例
    var scale : CGFloat = 0
    // 显示图像的URL
    var imgURL : NSURL? {
        didSet {
//            imgView.sd_setImageWithURL(imgURL, placeholderImage: nil) { (_, _, _, _) in
//                self.imgView.sizeToFit()
//            }
            SVProgressHUD.show()
            // 清空上一次cell中的图片视图
            imgView.image = nil
            // 使用sdwebImage下载图像
            SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: nil, progress: nil) { (image, error, _, _, _) in
                SVProgressHUD.dismiss()
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("图片加载失败")
                    return
                }
                self.setUpIamage(image)
            }
            
        }
    }
    
    // 计算图片大小
    private func setUpIamage(image:UIImage){
        JLog.i("下载的图片大小是:\(image.size)",false)
        let imgScaleSize = scaleImageSize(image)
        JLog.i("缩放后的图片尺寸为:\(imgScaleSize)",false)
        
        // 重置scrollView 
        resetScrollView()
        
        // 设置图像
        imgView.image = image
        // 设置图像尺寸
        imgView.frame = CGRectMake(0, 0, imgScaleSize.width, imgScaleSize.height)
        
        // 判断长短图 长图
        if imgScaleSize.height > view.bounds.height {
            // 置顶-滚动
            scrollView.contentSize = imgScaleSize
        } else {
            // 居中
            // 距离屏幕上方的距离为 (屏幕高度 - 图像高度) * 0.5
            let top = (view.bounds.height - imgScaleSize.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        }
    }
    
    // 计算图片缩放后的尺寸
    private func scaleImageSize(image : UIImage) -> CGSize {
        // 水平缩放的比例
        let wScale = image.size.width / view.bounds.width
        let height = image.size.height / wScale
        return CGSizeMake(view.bounds.width, height)
    }
    
    // 重置scrollView的属性
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    // 滚动视图
    lazy var scrollView : UIScrollView = {
        let sw = UIScrollView(frame: self.view.frame)
        // 要让scrollView支持缩放
        // 1.成为scrollView的代理
        sw.delegate = self
        
        // 2.设置最大最小缩放比例
        sw.maximumZoomScale = 2.0
        sw.minimumZoomScale = 0.5
        
        return sw
    }()
    
    // 照片视图 
    lazy var imgView : UIImageView = {
        let iv = UIImageView()
        return iv
//        // 添加捏合手势
//        let tap = UIPinchGestureRecognizer(target: self, action: "pinch:")
//        iv.addGestureRecognizer(tap)
//
//        // 记住UIImageView默认是不能与用户交互的!!!
//        iv.userInteractionEnabled = true
    }()
    
    // 纯代码开发
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        // 添加滚动视图
        view.addSubview(scrollView)
        // 将照片视图添加到滚动视图中
        scrollView.addSubview(imgView)
    }
    
    // 捏合手势触发事件
    func pinch(gesture:UIPinchGestureRecognizer){
        JLog.i("\(__FUNCTION__) \(gesture.scale)",false)
        scale = gesture.scale
        
        // 正在使用捏合手势
        if gesture.state == UIGestureRecognizerState.Changed {
            // 建立形变矩阵
            let transform = CGAffineTransformMakeScale(scale, scale)
            // 捏合手势使图片缩小
            if scale < 1.0 {
                startInteractiveTransition(self)
            } else {
                imgView.transform = CGAffineTransformMakeScale(gesture.scale,gesture.scale)
            }
        } else if gesture.state == UIGestureRecognizerState.Ended || gesture.state == UIGestureRecognizerState.Cancelled {
            // 捏合程度超过一半
            if scale < 0.5 {
                completeTransition(true)
            } else {
                // 回复照片原貌
                
            }
        }
        
    }
}

// 遵守交互式转场的协议
extension JPhotoViewerVC : UIViewControllerInteractiveTransitioning {
    // 开始交互转场动画
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 添加容器视图
        let toViewVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        let toView = toViewVC!.view
        // 把目标视图插入到当前控制器的视图下面就能显示出来了,那么view就不会被collectionViewCell所遮挡了 从运行时的视图结构可以看出来,这句话的作用
//         let dummyView = toView.snapshotViewAfterScreenUpdates(false)
        transitionContext.containerView().insertSubview(toView, belowSubview: view)
        // 虽然不会出现这种错误但是还是先照着写下快照视图
        // let dummy  = toView!.snapshotViewAfterScreenUpdates(false)
//        transitionContext.containerView().insertSubview(dummy, belowSubview: view)
        // 缩小视图并变浅
        view.transform = CGAffineTransformMakeScale(scale, scale)
        view.alpha = scale
    }
}

// 遵守UIViewControllerContextTransitioning协议
extension JPhotoViewerVC : UIViewControllerContextTransitioning {
    // 返回容器视图
    func containerView() -> UIView {
        return view.superview!
    }
    // 转场是否结束
    func completeTransition(didComplete: Bool) {
       dismissViewControllerAnimated(false, completion: nil)
    }
    
    // 提供转场到哪个控制器 运行效果和老师的不一样额
    func viewControllerForKey(key: String) -> UIViewController? {
        // 如果是目标控制器
        if key == UITransitionContextToViewControllerKey {
          return  UIApplication.sharedApplication().keyWindow?.rootViewController
        } else {
            return self
        }
    }
    // MARK: - 可以不调用的函数
    func isAnimated() -> Bool {
        return true
    }
    
    func isInteractive() -> Bool {
        return true
    }
    
    func transitionWasCancelled() -> Bool {
        return true
    }
    
    func presentationStyle() -> UIModalPresentationStyle {
        return UIModalPresentationStyle.Custom
    }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewForKey(key: String) -> UIView? {
        return nil
    }
    
    func targetTransform() -> CGAffineTransform {
        return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
}

// 遵守scrollViewDelegate协议
extension JPhotoViewerVC : UIScrollViewDelegate {
    // 哪个视图要进行缩放
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    
    // 结束手势缩放后被调用的方法
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
        // 重新计算缩放比例  证明交互式转场已经实现
        if scale < 1 {
            completeTransition(true)
            return
        }else {
            
        }
        // 重新计算离屏幕顶部的距离
        let top = (scrollView.bounds.height - view.frame.height) * 0.5
        if top > 0 {
            scrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        } else {
            // 顶部已经超出了屏幕顶部,设置距离顶部为0
            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
    }
    
    // 进行手势缩放被调用的方法 
    func scrollViewDidZoom(scrollView: UIScrollView) {
        // 可以根据transform来判断是缩小还是放大
        if imgView.transform.a < 1.0 {
            // 缩小
            scale = imgView.transform.a
            // 开始转场动画
            startInteractiveTransition(self)
        }
    }
}